﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Perceiveit.Xml.Tests
{
    public class PerformanceMarker
    {
        public string Category { get; set; }
        public string Action { get; set; }
        public double Duration { get; set; }

        public PerformanceMarker() { }

        public override string ToString()
        {
            return string.Format("{0}:{1} = {2}", Category, Action, Duration);
        }
    }

    public class PerformanceRun
    {
        private List<PerformanceMarker> _markers = new List<PerformanceMarker>(100);
        private System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
        private TimeSpan _last = TimeSpan.Zero;
        

        public string Category { get; set; }

        public List<PerformanceMarker> Markers
        {
            get { return _markers; }
        }

        public TimeSpan Total
        {
            get { return _last; }
        }

        public PerformanceRun(string category)
        {
            this.Category = category;
        }

        public void Begin()
        {
            _stopwatch.Start();
        }

        public void End()
        {
            _stopwatch.Stop();
            _last = _stopwatch.Elapsed;
            PerformanceMarker marker = new PerformanceMarker();
            marker.Category = this.Category;
            marker.Action = "Total";
            marker.Duration = _last.TotalMilliseconds;
            _markers.Add(marker);
            _stopwatch.Reset();
        }

        public void Mark(string action)
        {
            _stopwatch.Stop();
            PerformanceMarker marker = new PerformanceMarker();
            marker.Category = this.Category;
            marker.Action = action;
            marker.Duration = _stopwatch.Elapsed.TotalMilliseconds - _last.TotalMilliseconds;
            _markers.Add(marker);
            _last = _stopwatch.Elapsed;

            _stopwatch.Start();

        }
        
    }
}
